
import React, {useEffect} from "react";
import { usePathname, useRouter, useSearchParams} from "next/navigation";
import {getPersistToken, getToken, homeUrl, loginUrl, setToken} from "@/app/lib/security";
import {AuthorizationKey, getFetch} from "@/app/lib/HttpProtocol";
function  getIsLogin(){
  let token = getToken();
  return token != null;
}
function tryLogin(token:string|null){
  if(token == null){
    token = getPersistToken();
  }
  if(token == null){
    return false;
  }
  setToken(token);
  return true;
}
export default function Auth(){
  const pathname = usePathname();
  const router = useRouter();
  const params = useSearchParams();
  useEffect(() => {
    let isLogin = getIsLogin();
    if(!isLogin){
      isLogin = tryLogin(params.get(AuthorizationKey))
    }
    if(isLogin){
      if(pathname == loginUrl){
        router.push(homeUrl)
      }
    }else{
      if(pathname != loginUrl){
        router.push('/login')
      }
    }
  },[pathname,params])
  return <div></div>;
}